#pragma once

#include <poll.h>
#include <sys/epoll.h>
#include <string>
#include <cstring>
#include <functional>
#include "sock.hpp"
#include "err.hpp"

namespace epoll_ns
{
    const static int defaultfd = -1;
    const static uint16_t defaultport = 8080;
    const static int size = 128;
    const static int num = 1024;

    using func_t = std::function<std::string(const std::string &)>;

    class EpollServer
    {
    public:
        EpollServer(func_t f, uint16_t port = defaultport)
            : _func(f), _listensock(defaultfd), _port(port), _epfd(defaultfd), _revents(nullptr)
        {
        }

    public:
        void InitServer()
        {
            // 1.创建socket
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);

            // 2.创建epoll模型
            _epfd = epoll_create(size);
            if (_epfd == -1)
            {
                logMessage(FATAL, "epoll create error, errno: %d, error: %s", errno, strerror(errno));
                exit(EPOLL_CREATE_ERR);
            }
            // 3.将_listensock注册到epoll中
            struct epoll_event ep;
            ep.events = EPOLLIN;
            ep.data.fd = _listensock;
            epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock, &ep);
            // 4.申请就绪事件空间
            _revents = new struct epoll_event[num];
        }
        void Accepter()
        {
            std::string clientip;
            std::uint16_t clientport;
            int sock = Sock::Accept(_listensock, &clientip, &clientport);
            if (sock < 0)
            {
                logMessage(ERROR, "accept error");
                return;
            }
            // 不能直接从sock中读，因为不能保证sock底层缓冲区是否就绪，要将sock继续添加到epoll中
            struct epoll_event ep;
            ep.data.fd = sock;
            ep.events = EPOLLIN;
            epoll_ctl(_epfd, EPOLL_CTL_ADD, sock, &ep);
        }
        // 读取bug？？
        void ServiceIO(int fd)
        {
            char buffer[1024];
            ssize_t s = recv(fd, buffer, sizeof(buffer) - 1, 0);
            if (s > 0)
            {
                buffer[s] = 0;
                logMessage(NORMAL, "client # %s", buffer);
            }
            else if (s == 0)
            {
                epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
                close(fd);
                logMessage(NORMAL, "client quit");
            }
            else
            {
                epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
                close(fd);
                logMessage(ERROR, "read error");
            }
            std::string response = _func(buffer);
            send(fd, response.c_str(), response.size(), 0);
        }
        void HandlerReadEvent()
        {
            logMessage(DEBUG, "HandlerReadEvent in...");
            for (int i = 0; i < num; i++)
            {
                int fd = _revents[i].data.fd;
                if (_revents[i].events == EPOLLIN)
                {
                    // 如果是监听套接字就绪，建立连接
                    if (fd == _listensock)
                    {
                        Accepter();
                    }
                    // 如果是普通客户端套接字，处理IO
                    else
                    {
                        ServiceIO(fd);
                    }
                }
            }

            logMessage(DEBUG, "HandlerReadEvent out...");
        }
        void Start()
        {
            for (;;)
            {
                // 4.监控添加到epoll中的事件
                int timeout = -1;
                int n = epoll_wait(_epfd, _revents, num, timeout);
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout...");
                    break;
                case -1:
                    logMessage(WARNING, "epoll wait error");
                    break;
                default:
                    logMessage(NORMAL, "have event ready...");
                    HandlerReadEvent();
                    break;
                }
            }
        }

    private:
        int _listensock;
        uint16_t _port;
        int _epfd;
        struct epoll_event *_revents;
        func_t _func;
    };

}